package com.jade.journal.appender;

import java.io.File;

import com.jade.framework.base.util.DataUtils;
import com.jade.framework.base.util.SimpleDate;
import com.jade.journal.JournalEvent;
import com.jade.journal.desc.AppenderDesc;
import com.jade.journal.desc.JournalDesc;

/**
 * 每日文件的追加器。
 *
 * @author sky
 * @version 1.0 14-9-22 下午3:50
 */
public class DailyFileAppender extends DailyAppender
{
    public static final String TYPE = "daily_file";
    /** 日志输出文件名 */
    private String fileName;

    public DailyFileAppender(JournalDesc desc, AppenderDesc appenderDesc)
    {
        super(TYPE, desc, appenderDesc);
    }

    /**
     * 设置日志输出的文件名
     *
     * @param fileName 日志输出文件名(非绝对)
     */
    public void setFileName(String fileName)
    {
        this.fileName = fileName;
    }

    protected AppenderDesc fileAppenderDesc;

    @Override
    public void init(JournalEvent event)
    {
        super.init(event);
        fileName = DataUtils.getString(appenderDesc.getProperty("fileName"), desc.getName());
        fileAppenderDesc = new AppenderDesc();
        fileAppenderDesc.setType(FileAppender.TYPE);
        fileAppenderDesc.setProps(appenderDesc.getProps());
    }

    protected StreamAppender createAppender(SimpleDate date, String absolute)
    {
        FileAppender appender = new FileAppender(desc, fileAppenderDesc);
        appender.setEncoding(getEncoding());
        appender.setFormat(getFormat());
        appender.setFile(new File(absolute));
        return appender;
    }

    protected String toAbsolute(SimpleDate date)
    {
        StringBuilder sb = new StringBuilder();
        sb.append(getPath()).append(File.separatorChar);
        date.format(sb, (char)0).append(File.separatorChar);
        if (fileName != null) {
            sb.append(fileName);
        }
        else {
            sb.append(getName());
        }
        return sb.toString();
    }
}
